class ScoreTable
{
	score_table = null;

	constructor()
	{
		// A table of companyId/score for all existing comps
		this.score_table = {};
	}
}

function ScoreTable::AddCompany(companyId)
{
	local nextCompanyId = next_companyId(companyId);
	this.score_table[nextCompanyId] <- { score=0, exists=true, name=GSCompany.GetName(companyId) };
	GSLog.Info("Added company: "+nextCompanyId);
}

function ScoreTable::IncreaseScore(companyId, score)
{
	local realCompanyId = real_companyId(companyId);
	this.score_table[realCompanyId].score += score;
	GSLog.Info("Increased score for " + realCompanyId);
}

function ScoreTable::RemoveCompany(companyId)
{
	local realCompanyId = real_companyId(companyId);
	GSLog.Info("Remove company with id: " + realCompanyId);
	this.score_table[realCompanyId].exists = false;
}

function ScoreTable::RenameCompany(companyId, companyName)
{
	local realCompanyId = real_companyId(companyId);
	GSLog.Info("Company changed name to: " + companyName);
	this.score_table[realCompanyId].name = companyName;
}

function get_companyId_offset(i)
{
	local offset = null;
	local next_offset = 0;
	local current_key = i+"."+next_offset;

	GSLog.Info("Looking for company with ID: "+i+".x");

	while (current_key in this.score_table)
	{
		GSLog.Info("Found company ID: " + current_key);
		offset = next_offset;
		next_offset += 1;
		current_key = i+"."+next_offset;
	}

	return offset;
}

function real_companyId(i)
{
	return i+"."+get_companyId_offset(i);
}

function next_companyId(i)
{
	local offset = get_companyId_offset(i);
	if (offset == null)
	{
		return i+".0";
	} else {
		offset += 1;
		return i+"."+offset;
	}
}

function company_compare(a,b)
{
	if (a.score>b.score) return 1
	else if (a.score<b.score) return -1
	return 0;
}

function ScoreTable::GetScoreTableAsList()
{
	local companyList = [];
	foreach(companyId, companyObj in this.score_table)
	{
		companyList.append(companyObj);
	}

	companyList.sort(company_compare);
	companyList.reverse();
	return companyList;
}
